<template>
  <div>
    <h2>文章列表</h2>
    <el-table :data="articles" style="width: 100%">
      <el-table-column prop="title" label="标题"></el-table-column>
      <el-table-column prop="content" label="内容"></el-table-column>
      <el-table-column prop="status" label="是否公开">
        <template #default="{ row }">
          <el-switch
            v-model="row.status"
            class="ml-2"
            style="
              --el-switch-on-color: #13ce66;
              --el-switch-off-color: #ff4949;
            "
            disabled
          />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button plain @click="editArticle(row)"> 编辑 </el-button>
          <el-button @click="deleteArticle(row.id)" type="danger"> 删除 </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑对话框 -->
    <el-dialog v-model="dialogFormVisible" title="编辑文章" width="500px">
      <el-form :model="currentArticle">
        <el-form-item label="标题" :label-width="formLabelWidth">
          <el-input v-model="currentArticle.title" autocomplete="off" />
        </el-form-item>
        <el-form-item label="内容" :label-width="formLabelWidth">
          <el-input v-model="currentArticle.content" autocomplete="off" />
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-switch v-model="currentArticle.status" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="saveChanges">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import http from "../utils/http";

const articles = ref([]);
const dialogFormVisible = ref(false);
const currentArticle = ref({
  id: "",
  title: "",
  content: "",
  status: true,
});

const fetchArticles = async () => {
  try {
    const response = await http.get("/posts");
    articles.value = response.data;
  } catch (error) {
    console.error("获取文章列表失败:", error);
  }
};

const saveChanges = async () => {
  try {
    await http.patch(`/posts/${currentArticle.value.id}`, {
      title: currentArticle.value.title,
      content: currentArticle.value.content,
      status: currentArticle.value.status,
    });
    alert("文章更新成功!");
    dialogFormVisible.value = false;
    fetchArticles(); 
  } catch (error) {
    alert("更新文章失败!");
  }
};

const deleteArticle = async (id) => {
  try {
    await http.delete(`/posts/${id}`);
    alert("文章删除成功!");
    fetchArticles(); 
  } catch (error) {
    alert("删除文章失败!");
  }
};

const editArticle = (article) => {
  currentArticle.value = { ...article }; 
  dialogFormVisible.value = true; 
};

onMounted(() => {
  fetchArticles();
});
</script>
